package com.xy.xylive.api;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;

import com.xy.xylive.aop.NoSign;
import com.xy.xylive.api.req.GetLiveReq;
import com.xy.xylive.api.req.SignReq;
import com.xy.xylive.common.SM3Util;
import com.xy.xylive.common.ServiceException;
import com.xy.xylive.common.ServletUtils;
import com.xy.xylive.config.ApplicationConfig;
import com.xy.xylive.xyapi.LiveVideoRes;
import com.xy.xylive.xyapi.LiveVideoV5Api;
import com.xylink.config.SDKConfigMgr;
import com.xylink.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    @NoSign
    public R<Map<String, String>> uploadFile(MultipartFile file) throws Exception
    {
        log.info("upload....");
        if (file == null) {
            throw new ServiceException("文件不能为空");
        }
        try
        {
            // 上传文件路径
            String filePath = ApplicationConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = upload(filePath, file);
            String url = getUrl() + fileName;
            Map<String, String> data = new HashMap<>();
            data.put("url", url);
            data.put("fileName", fileName);
            return R.ok(data);
        }
        catch (Exception e)
        {
            log.error("upload error:{}", e);
            return R.fail("上传失败");
        }
    }

    public String getUrl()
    {
        HttpServletRequest request = ServletUtils.getRequest();
        return getDomain(request);
    }

    private String getDomain(HttpServletRequest request)
    {
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
    }

    private File getAbsoluteFile(String uploadDir, String fileName)
    {
        File desc = new File(uploadDir + File.separator + fileName);

        if (!desc.exists())
        {
            if (!desc.getParentFile().exists())
            {
                desc.getParentFile().mkdirs();
            }
        }
        return desc;
    }

    private String upload(String baseDir, MultipartFile file) throws IOException {
        String fileName = StrUtil.format("{}_{}.{}", FileNameUtil.getPrefix(file.getOriginalFilename()), IdUtil.simpleUUID(), FileNameUtil.getSuffix(file.getOriginalFilename()));
        String absPath = getAbsoluteFile(baseDir, fileName).getAbsolutePath();
        file.transferTo(Paths.get(absPath));
        return "/upload/" + fileName;
    }

    @PostMapping("/checkSign")
    public R<Boolean> checkSign(@RequestBody SignReq signReq) {
        if(StrUtil.hasBlank(signReq.getUserId(), signReq.getMeetingId(), signReq.getSuperAdmin(), signReq.getTimeStamp(), signReq.getSign())) {
            throw new ServiceException("缺少必要参数");
        }
        // timeStamp|userId|meetingNumber|superAdmin|salt
        // salt为固定字符串"ChinaTower"
        String sign = SM3Util.encrypt(signReq.getTimeStamp() + "|" + signReq.getUserId() + "|" + signReq.getMeetingId() + "|" + signReq.getSuperAdmin() + "|ChinaTower");
        log.info("checkSign sign:{}", sign);
        Boolean result = Objects.equals(sign, signReq.getSign());
        return R.ok(result);
    }
}
